<template>
  <div class="staff-wrapper">
    <el-row>
      <el-col :span="6">
        <div class="grid-content bg-purple">
          <el-alert
            center
            type="info"
            show-icon
            class="custom-class"
            :title="`共${staffList.total}条记录`"
            :closable="false"
          >
          </el-alert>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="grid-content bg-purple-light">
          <el-button type="danger" size="small">普通excel导出</el-button>
          <el-button type="info" size="small">复杂表头excel导出</el-button>
          <el-button type="success" size="small">excel导入</el-button>
          <el-button type="primary" size="small" @click="openAddVisible">新增员工</el-button>
        </div>
      </el-col>
    </el-row>
    <div class="table-wrapper">
      <!-- 中间表格部分 -->
      <custom-table
        :data="staffList.rows"
        :columns="columns"
        :total="staffList.total"
        :current-page.sync="page.current"
        :page-size.sync="page.size"
        @update:currentPage="onPageChange"
        @update:pageSize="onPageSizeChange"
      >
        <template v-slot="{ row, col, data }">
          <div class="demo-basic--circle">
            <div class="block">
              <el-avatar
                v-if="col.prop === 'staffPhoto'"
                :size="50"
                :src="data"
              >
              </el-avatar>
            </div>
          </div>
          <span v-if="col.prop === 'formOfEmployment'">
            {{ formOfEmploymentMapping[data] }}
          </span>
          <el-switch disabled v-if="col.prop === 'state'"> </el-switch>
          <template v-if="col.prop === 'op'">
            <el-button type="text" size="mini">查看</el-button>
            <el-button type="text" size="mini">转正</el-button>
            <el-button type="text" size="mini">调岗</el-button>
            <el-button type="text" size="mini">离职</el-button>
            <el-button type="text" size="mini" @click="openRoleVisible(row.id)">角色</el-button>
            <el-button type="text" size="mini" @click="onDelete(row.id)">删除</el-button>
          </template>
        </template>
      </custom-table>
    </div>
    <!-- 新增员工对话框 -->
    <el-dialog title="新增员工" :visible.sync="addVisible" center destroy-on-close>
      <el-form :model="addForm" :rules="addRules">
        <el-form-item label="姓名" :label-width="formLabelidth" prop="username">
          <el-input
            v-model="addForm.username"
            autocomplete="off"
            placeholder="请输入姓名"
            class="change-width"
          />
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelidth" prop="mobile">
          <el-input
            v-model="addForm.mobile"
            autocomplete="off"
            placeholder="请输入手机号"
            class="change-width"
          />
        </el-form-item>
        <el-form-item
          label="入职时间"
          prop="timeOfEntry"
          :label-width="formLabelidth"
        >
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="请选择入职时间"
              v-model="addForm.timeOfEntry"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item
          label="聘用形式"
          prop="formOfEmployment"
          :label-width="formLabelidth"
        >
          <el-select
            placeholder="请选择聘用形式"
            v-model="addForm.formOfEmployment"
          >
            <el-option label="正式" value="1"></el-option>
            <el-option label="非正式" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="工号"
          prop="workNumber"
          :label-width="formLabelidth"
        >
          <el-input
            v-model="addForm.workNumber"
            autocomplete="off"
            placeholder="请输入工号"
            class="change-width"
          />
        </el-form-item>
        <el-form-item
          label="部门"
          prop="departmentName"
          :label-width="formLabelidth"
        >
          <el-input
            ref="departmentName"
            :value="addForm.departmentName"
            autocomplete="off"
            placeholder="请选择部门名称"
           @focus="onDepartmentTreeExpand"
            class="change-width"
          >
          </el-input>
          <el-tree
            v-if="departmentVisible"
            ref="tree"
            default-expand-all
            node-key="name"
            :data="newDepartmentList"
            :props="{ children: 'children', label: 'name' }"
            @node-click="handleNodeClick"
          >
          </el-tree>
        </el-form-item>
        <el-form-item
          label="转正时间"
          prop="correctionTime"
          :label-width="formLabelidth"
        >
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="请选择转正时间"
              v-model="addForm.correctionTime"
            >
            </el-date-picker>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onAddStaff"> 确定 </el-button>
        <el-button @click="addVisible = false"> 取消 </el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleVisible" center>
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="role in rolesList.rows"
          :key="role.id"
          :label="role.id"
          >
            {{ role.name }}
          </el-checkbox
        >
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onAssignRoles"> 确定 </el-button>
        <el-button @click="roleVisible = false"> 取消 </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 验证表单选择是否为空
function getCheckFunc(field) {
  return function (rule, value, callback) {
    if (!value) {
      callback(new Error(this.$t("staffManagement.dialogTip.add." + field)));
    } else {
      callback();
    }
  };
}
// 验证手机号格式是否正确
function getCheckTel(field) {
  return function (rule, value, callback) {
    if (!/^[1][3,5,7,8][0-9]\d{8}$/.test(value)) {
      callback(new Error("手机号码格式错误"));
    } else {
      callback();
    }
  };
}
// 验证部门名称是否为空
function checkDepartmentName (rule, value, callback) {
  if (value === '请选择部门') {
    callback(new Error(this.$t('staffManagement.dialogTip.add.departmentName')));
  } else {
    callback();
  }
}
let currentId = -1;
import * as staffManagement from "@/api/staff-management";
import { mapState, mapActions } from "vuex";
export default {
  data() {
    return {
      // 新增对话框是否显示
      addVisible: false,
      // 是否显示部门信息
      departmentVisible: false,
      // 是否显示角色对话框
      roleVisible: false,
      // 复选框默认被选中的数组
      checkList: [],
      // 新增对话框绑定数据
      addForm: {
        formOfEmployment: 1,
        departmentName: '请选择部门',
      },
      formLabelidth: "140px",
      // 新增的验证规则
      addRules: {
        username: [
          {
            required: true,
            trigger: "blur",
            validator: getCheckFunc("fullName").bind(this),
          },
          {
            min: 2,
            max: 4,
            message: "员工姓名为 2 ~ 4 个字符",
            trigger: "blur",
          },
        ],
        mobile: [
          {
            required: true,
            trigger: "blur",
            validator: getCheckFunc("mobile").bind(this),
          },
          {
            trigger: "blur",
            validator: getCheckTel("mobile").bind(this),
          },
        ],
        timeOfEntry: [
          {
            required: true,
            trigger: "blur",
            validator: getCheckFunc("timeOfEntry").bind(this),
          },
        ],
        formOfEmployment: [
          {
            required: true,
            trigger: "blur",
            message: "请选择聘用形式",
          },
        ],
        workNumber: [
          {
            required: true,
            trigger: "blur",
            validator: getCheckFunc("workNumber").bind(this),
          },
          {
            min: 3,
            max: 4,
            message: "员工工号为 3 ~ 4 位数字",
            trigger: "blur",
          },
        ],
        departmentName: [
          {
            required: true,
            trigger: 'blur',
            validator: checkDepartmentName.bind(this)
          }
        ],
      },
      page: {
        current: 1,
        size: 5,
      },
      // 表格组件传参
      formOfEmploymentMapping: {
        0: "外包",
        1: "正式",
        2: "外聘",
      },
      currentPage: 1,
      columns: [
        {
          label: "序号",
          // 没有prop的时候 显示索引
          width: 100,
        },
        {
          label: "姓名",
          prop: "username",
          sortable: true,
        },
        {
          label: "头像",
          prop: "staffPhoto",
          needSlot: true,
        },
        {
          label: "手机号",
          prop: "mobile",
          sortable: true,
        },
        {
          label: "工号",
          prop: "workNumber",
          sortable: true,
        },
        {
          label: "聘用形式",
          prop: "formOfEmployment",
          sortable: true,
        },
        {
          label: "部门",
          prop: "departmentName",
          sortable: true,
        },
        {
          label: "入职时间",
          prop: "timeOfEntry",
          sortable: true,
        },
        {
          label: "状态",
          prop: "state",
          needSlot: true,
        },
        {
          label: "操作",
          prop: "op",
          width: 230,
          needSlot: true,
          fixed: "right",
        },
      ],
    };
  },
  computed: {
    ...mapState("staff-management", [
      "staffList",
      "departmentList",
      "staffRoleInfo",
    ]),
    ...mapState("company-setting", ["rolesList"]),
    newDepartmentList() {
      return tool.getTreeData(departmentList.depts.filter(d => d.pid !== '-1'), '')
    }
  },
  methods: {
    ...mapActions("staff-management", [
      "updateStaffList",
      "updateDepartmentList",
      "updateRoleInfo",
    ]),
    ...mapActions("company-setting", ["updateRolesList"]),
    // 展开部门列表
    onDepartmentTreeExpand () {
      this.departmentVisible = true;
    },
    // 给选择部门赋值
    handleNodeClick() {
      // 手动设置焦点
      this.$refs.departmentName.focus();
      // input赋值
      this.addForm.departmentName = this.$refs.tree.getCurrentKey();
      this.departmentVisible = false;
      // 手动失去焦点
      this.$refs.departmentName.blur();
    },
    // 获取所有员工列表
    async getStaffList() {
      await this.updateStaffList({
        params: {
          page: this.page.current,
          size: this.page.size,
        },
      });
    },
    // 分配角色选中值发生改变时
    // handleChange: function (e, id) {
    //   if (e) {
    //     this.checkList.push(id);
    //   } else {
    //     this.checkList = this.checkList.filter((item) => item !== id);
    //   }
    // },
    // 打开分配角色对话框 根据id获取用户的角色列表
    async openRoleVisible(id) {
      this.roleVisible = true;
      currentId = id;
      const res = await this.updateRoleInfo(id);
      this.checkList = this.staffRoleInfo || [];
    },
    // 给用户分配角色
    async onAssignRoles() {
      // this.checkList = tool.unique(this.checkList);
      const res = await staffManagement.assignRoles({
        id: currentId,
        roleIds: this.checkList,
      });
      this.$message({
        message: res.message,
        type: res.success ? "success" : "error",
      });
      if (res.success) {
        this.roleVisible = false;
        this.checkList = [];
      }
    },
    // 打开新增员工对话框
    openAddVisible() {
      this.addVisible = true;
    },
    // 添加用户
    async onAddStaff() {
      const res = await staffManagement.addStaff({
        ...this.addForm,
      });
      this.$message({
        message: res.message,
        type: res.success ? "success" : "error",
      });
      if (res.success) {
        // 刷新员工列表
        await this.getStaffList();
        this.addVisible = false;
        // 表单置空
        this.addForm = {
          formOfEmployment: 1,
          departmentName: '请选择部门',
        };
        }
    },
    // 删除用户
    onDelete(id) {
      this.$confirm("确定删除该用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(async () => {
        const res = await staffManagement.delStaff(id);
        this.$message({
          message: res.message,
          type: res.success ? "success" : "error",
        });
        if (res.success) {
          await this.getStaffList();
        }
      });
    },
    // 分页切换
    onPageChange(currentPage) {
      this.updateStaffList({
        page: currentPage,
        size: this.page.size,
      });
    },
    // 分页条数切换
    onPageSizeChange(pageSize) {
      this.updateStaffList({
        page: 1,
        size: pageSize,
      });
    },
  },
  async created() {
    // 获取所有员工列表
    await this.getStaffList();
    // 获取所有部门列表
    await this.updateDepartmentList();
    // 获取所有角色列表
    await this.updateRolesList();
  },
};
</script>
<style lang="scss" scoped>
.staff-wrapper {
  padding: 0 16px;
  box-sizing: border-box;
  .custom-class {
    width: 150px;
    background-color: #e6f7ff;
    color: #409eff;
  }
  .el-row {
    padding: 10px;
    box-sizing: border-box;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;
    border: 1px solid #eee;
    border-radius: 4px;
  }
  .bg-purple-light {
    justify-content: flex-end;
  }
  .bg-purple-light,
  .bg-purple {
    display: flex;
    align-items: center;
  }
  .bg-purple-dark {
    align-items: flex-start;
  }
  .grid-content {
    min-height: 60px;
  }
  .change-width {
    width: 300px;
  }
  .table-wrapper {
    margin-top: 12px;
    padding: 16px;
    box-sizing: border-box;
    border: 1px solid #eee;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}
</style>